from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

from app01.models import *
from django import forms
from django.forms import widgets
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError


class USERINFO(forms.Form):
    user = forms.CharField(min_length=2, label="用户名", error_messages={"required": "不能为空", "min_length": "至少为2位"})
    pwd = forms.CharField(min_length=2, label="密码", error_messages={"required": "不能为空", "min_length": "至少为2位"},
                          widget=widgets.PasswordInput)


def login(request):
    form = USERINFO(request.POST)
    if request.method == "POST":

        ret = Users.objects.filter(user=request.POST.get("user"), pwd=request.POST.get("pwd")).first()
        if form.is_valid() and ret:
            res = redirect("/index")
            res.set_cookie("is_login", True)
            return res

    return render(request, 'login.html', {"form": form})


def index(request):
    res = request.COOKIES.get("is_login")
    print(res)
    if res:
        return render(request, 'index.html')
    else:
        return redirect("/login")
